package xyz.qduwo.servlet;

import org.apache.commons.fileupload.FileUploadException;
import xyz.qduwo.dao.UserDao;
import xyz.qduwo.entity.UserEntity;
import xyz.qduwo.util.EncryptUtils;
import xyz.qduwo.util.FileForm;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 *
 */
@WebServlet(name = "RegisterServlet", urlPatterns = { "/RegisterServlet" })
public class RegisterServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
        try {
            String dir_path = getServletContext().getRealPath("/upload/avatar");
            FileForm fileForm = new FileForm(request,dir_path,"/upload/avatar");
            Map<String,String> formFiledMap= fileForm.getFormFiledMap();
            String avatar = formFiledMap.get("avatar");
            String username = formFiledMap.get("username");
            String email = formFiledMap.get("email");
            String nickname = formFiledMap.get("nickname");
            String password = EncryptUtils.stringToMD5(formFiledMap.get("password")); //调用加密方法进行MD5加密
            UserEntity user = new UserEntity();
            user.setPassword(password);
            user.setUsername(username);
            user.setAvator(avatar);
            user.setEmail(email);
            user.setNickname(nickname);
            UserDao.save(user);
            response.sendRedirect("login.jsp");


        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
